import { useEffect, useState } from "react";
import MyModal from "../MyModal";
import { useModel } from "@umijs/max";
import { login, register } from '@/services/user/user';
import { setToken, } from '@/utils/info';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message } from 'antd';
import styles from './index.less';
import { useRequest } from "@umijs/max";

export default () => {
    const [form] = Form.useForm();
    const {showLogin,setShowLogin,changeUserInfo,userInfo} = useModel('global')
    const [type, setType] = useState(1);
    const { run: loginFun } = useRequest(type===1?login:register, {
      manual: true, // 手动触发
      onSuccess: (res) => {
        if (res instanceof Error) return;
        setToken(res?.token||'');
        changeUserInfo(res);
        message.success('登录成功');
        setShowLogin(false)
      },
    });
    const onFinish = async (values: any) => {
      await form.validateFields();
      loginFun(values);
    };
    return <MyModal title="IT技术论坛" zIndex={99999} open={showLogin} footer={null}  close={() => {setShowLogin(false)}}>
        <div className={styles.loginContent}>
          <Form form={form} onFinish={onFinish}>
            <div className={styles.type}>
                  <span
                    className={`${type === 1 && styles.active}`}
                    onClick={() => setType(1)}
                  >
                    登录
                  </span>
                  <span
                    className={`${type === 2 && styles.active}`}
                    onClick={() => setType(2)}
                  >
                    注册
                  </span>
            </div>
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入账号' }]}
            >
              <Input prefix={<UserOutlined />} placeholder="账号" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="密码" />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ width: '100%' }}
              >
                {type === 1?'登录':'注册'}
              </Button>
            </Form.Item>
          </Form>
        </div>
    </MyModal>
};